package com.heimo.babyage;

import java.io.FileNotFoundException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.ads.AdView;
import com.heimo.babyage.core.DateHelper;
import com.heimo.babyage.core.LogHelper;
import com.heimo.babyage.core.PrefHelper;
import com.heimo.babyage.ui.dialog.DialogHelper;
import com.heimo.babyage.ui.framegrid.FramePickerAdapter;
import com.heimo.babyage.ui.framegrid.FramePickerDialog;
import com.heimo.babyage.ui.framegrid.OnFramePickedListener;

public class PreferenceActivity extends BasicActivity {
	private static final String TAG = "PreferenceActivity";

	private Button prefDOB, prefFrame, btnClose;
	private ImageView chosenImageView, imgOverlay;
	private TextView dobLab, frameLab, imgLab, seekbarAlphaLab;
	private SeekBar seekbarAlpha;
	private String seekLabel;

	private final int CHOOSE = 0;
	private final int CHOP = 1;
	private final int PREVIEW = 2;
	
	//TODO Add selector for font size & display date pattern
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pref);

		// Set the result to CANCELED. This will cause the widget host to cancel
		// out of the widget placement if they press the back button.
		// setResult(RESULT_CANCELED);

		dobLab = (TextView) findViewById(R.id.title_dob);
		prefDOB = (Button) findViewById(R.id.btn_dob);

		frameLab = (TextView) findViewById(R.id.title_frame);
		prefFrame = (Button) findViewById(R.id.btn_frame);

		imgLab = (TextView) findViewById(R.id.title_image);
		chosenImageView = (ImageView) findViewById(R.id.img_photo);
		imgOverlay = (ImageView) findViewById(R.id.img_overlay);

		seekbarAlphaLab = (TextView) findViewById(R.id.title_alpha);
		seekbarAlpha = (SeekBar) findViewById(R.id.seekbar_alpha);
		seekLabel = this.getString(R.string.lab_alpha);

		btnClose = (Button) findViewById(R.id.btn_close);

		fnRemoveAdView();
		initData();
		initFontFace();
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		for(int i = 0 ; i<menu.size();i++){
			MenuItem item = menu.getItem(i);
			int id = item.getItemId();
			if(id == R.id.action_sponsor || id == R.id.action_settings){
				item.setVisible(true);
			}
		}
		return true;
	}
	
	private void fnRemoveAdView() {
		if (PrefHelper.hasSponsor(this) == true || BuildConfig.DEBUG) {
			LinearLayout layout = (LinearLayout) findViewById(R.id.adViewLayout);
			AdView adView = (AdView) findViewById(R.id.adView);
			layout.removeView(adView);
		}
	}

	private void initFontFace() {
		Typeface tf = Typeface.createFromAsset(getAssets(),
				"fonts/orbitron-bold.otf");
		if(tf!=null){
			dobLab.setTypeface(tf);
			prefDOB.setTypeface(tf);
			frameLab.setTypeface(tf);
			prefFrame.setTypeface(tf);
			imgLab.setTypeface(tf);
			seekbarAlphaLab.setTypeface(tf);
			btnClose.setTypeface(tf);
		}
	}

	private void initData() {
		fnGetWidgetId();
		// init Bday
		Date d = PrefHelper.fnLoadBDayPref(this, mAppWidgetId);
		prefDOB.setText(DateHelper.getDateFormatter().format(d));

		// init Alpha
		int alpha = PrefHelper.fnLoadAlphaPref(this, mAppWidgetId);
		seekbarAlpha.setMax(255);
		seekbarAlpha.setProgress(alpha);
		seekbarAlphaLab.setText(seekLabel + alpha);
		fnSetSeekBarListener(seekbarAlpha);

		// init Frame
		int framePos = PrefHelper.fnLoadFramePref(this, mAppWidgetId);
		if (framePos == 0) {
			prefFrame.setText("N/A");
			imgOverlay.setVisibility(View.GONE);
		} else {
			FramePickerAdapter fpa = new FramePickerAdapter(this);
			int imgID = fpa.getImageIdByPos(framePos);
			prefFrame.setText(framePos + "");
			imgOverlay.setVisibility(View.VISIBLE);
			imgOverlay.setImageResource(imgID);
		}

		// init Image
		Bitmap bm = PrefHelper.fnLoadImage(this, mAppWidgetId);
		chosenImageView.setImageBitmap(bm);
	}
	
	@Override
	protected void fnUpdateView() {
		RemoteViews rv = new RemoteViews(this.getPackageName(),
				R.layout.widget_layout_1);

		// Update Age
		Date d = PrefHelper.fnLoadBDayPref(this, mAppWidgetId);
		rv.setTextViewText(R.id.counter_text, DateHelper.getDateFormatter()
				.format(d));

		// Update Alpha
		int alpha = PrefHelper.fnLoadAlphaPref(this, mAppWidgetId);
		rv.setInt(R.id.baby_img, "setAlpha", alpha);
		// Update Preview Alpha
		chosenImageView.setAlpha(alpha);

		// Update Image
		Bitmap bm = PrefHelper.fnLoadImage(this, mAppWidgetId);
		rv.setImageViewBitmap(R.id.baby_img, bm);

		// Update Image Overlay Frame
		int framePos = PrefHelper.fnLoadFramePref(this, mAppWidgetId);
		if (framePos == 0) {
			rv.setViewVisibility(R.id.overlay, View.GONE);
			prefFrame.setText("N/A");
			imgOverlay.setVisibility(View.GONE);
		} else {
			rv.setViewVisibility(R.id.overlay, View.VISIBLE);
			FramePickerAdapter fpa = new FramePickerAdapter(this);
			int imgID = fpa.getImageIdByPos(framePos);

			rv.setImageViewResource(R.id.overlay, imgID);
			prefFrame.setText(framePos + "");
			imgOverlay.setVisibility(View.VISIBLE);
			imgOverlay.setImageResource(imgID);
			// rv.setInt(R.id.overlay, "setAlpha", alpha);
		}
		super.fnUpdateView();
	}

	public void fnLoadPhoto(View v) {
		Intent i = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(Intent.createChooser(i, "Select Image"), CHOOSE);
	}

	public void fnLoadBirthday(View v) {
		final Context ctx = this;
		final DatePickerDialog.OnDateSetListener myDateSetListener = new DatePickerDialog.OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				String setDt = String.valueOf(year) + "-"
						+ String.valueOf(monthOfYear + 1) + "-"
						+ String.valueOf(dayOfMonth);
				prefDOB.setText(setDt);

				Calendar c = Calendar.getInstance();
				c.set(year, monthOfYear, dayOfMonth);
				PrefHelper.fnSaveBDayPref(ctx, mAppWidgetId, c.getTime());
				fnUpdateView();
			}
		};
		Date d = PrefHelper.fnLoadBDayPref(this, mAppWidgetId);
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		int mYear = c.get(Calendar.YEAR);
		int mMonth = c.get(Calendar.MONTH);
		int mDay = c.get(Calendar.DATE);
		DatePickerDialog dpd = new DatePickerDialog(this, myDateSetListener,
				mYear, mMonth, mDay);
		dpd.setTitle(R.string.title_pick_dob);
		dpd.show();
	}

	public void fnLoadFrame(View v) {
		final Context ctx = this;
		OnFramePickedListener cb = new OnFramePickedListener() {

			@Override
			public void framePicked(int frame) {
				PrefHelper.fnSaveFramePref(ctx, mAppWidgetId, frame);
				fnUpdateView();
				Toast.makeText(ctx, "Frame : " + frame, Toast.LENGTH_LONG)
						.show();
			}

		};
		FramePickerDialog fpd = new FramePickerDialog(this, cb);
		fpd.show();
	}

	private void fnGetWidgetId() {
		Intent intent = getIntent();
		Bundle extras = intent.getExtras();
		mAppWidgetId = -1;
		if (extras != null) {
			mAppWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
					AppWidgetManager.INVALID_APPWIDGET_ID);
		}
		LogHelper.log(TAG, "fnGetWidgetId : " + mAppWidgetId);
		// If they gave us an intent without the widget id, just bail.
		if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
			finish();
		}
	}

	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		if (resultCode == RESULT_OK) {
			LogHelper.log(TAG, "requestCode:" + requestCode);
			switch (requestCode) {
			case CHOOSE:
				// fnChooseImage(intent);
				fnPostSelectImage(intent);
				break;
			case CHOP:
				fnPostChopImage(intent);
				break;
			case PREVIEW:
				break;
			}
		} else {
			LogHelper.log(TAG, "Request Fail code :" + requestCode);
		}
	}

	private void fnChooseImage(Intent intent) {
		Uri imageUri = intent.getData();

		Display currentDisplay = getWindowManager().getDefaultDisplay();
		int dw = currentDisplay.getWidth();
		int dh = currentDisplay.getHeight() / 2 - 100;
		try {
			BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
			bmpFactoryOptions.inJustDecodeBounds = true;
			Bitmap bmp = BitmapFactory.decodeStream(getContentResolver()
					.openInputStream(imageUri), null, bmpFactoryOptions);
			// Compression Ratio
			bmpFactoryOptions.inSampleSize = 1;
			bmpFactoryOptions.inJustDecodeBounds = false;
			bmp = BitmapFactory.decodeStream(getContentResolver()
					.openInputStream(imageUri), null, bmpFactoryOptions);
			chosenImageView.setImageBitmap(bmp);
		} catch (FileNotFoundException e) {
			LogHelper.log("ERROR", e.toString());
		}
	}

	public void fnPostSelectImage(Intent i) {
		final Intent intent = i;
		String[] sizeArray = new String[] { "4:3", "16:9", "Free" };
		OnClickListener selection = new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int sel) {
				dialog.dismiss();
				LogHelper.log(TAG, "onClick : " + sel);
				switch (sel) {
				case 0:
					fnChop(intent, 4, 3, 200, 150);
					break;
				case 1:
					fnChop(intent, 16, 9, 200, 112);
					break;
				case 2:
					fnChop(intent, -1, -1, -1, -1);
					break;
				default:
					break;
				}
			}
		};
		AlertDialog dialog = DialogHelper.getSingleOptionDialog(this,
				"Chop Size", sizeArray, selection);
		dialog.show();
	}

	private void fnChop(Intent i, int aspectX, int aspectY, int outputX,
			int outputY) {
		List<ResolveInfo> list = getPackageManager()
				.queryIntentActivities(i, 0);
		int size = list.size();
		if (size == 0) {
			Toast.makeText(this, "Can not find image crop app",
					Toast.LENGTH_SHORT).show();
			fnPostChopImage(i);
			return;
		} else {
			Uri imageUri = i.getData();
			if (imageUri != null) {
				Intent ic = new Intent("com.android.camera.action.CROP");
				// indicate image type and Uri
				ic.setDataAndType(imageUri, "image/*");
				// set crop properties
				ic.putExtra("crop", "true");
				
				if(aspectX >0 && aspectY>0){
					// indicate aspect of desired crop, as ratio
					ic.putExtra("aspectX", aspectX);
					ic.putExtra("aspectY", aspectY);					
				}
				
				if(outputX >0 && outputY>0){
					// indicate output X and Y 100x 100y
					ic.putExtra("outputX", outputX);
					ic.putExtra("outputY", outputY);
				}
				
				// retrieve data on return
				ic.putExtra("return-data", true);
				// start the activity - we handle returning in onActivityResult
				// startActivityForResult(cropIntent, CHOP);
				try {
					startActivityForResult(
							Intent.createChooser(ic, "Chop Image"), CHOP);
				} catch (Exception e) {
					LogHelper.log(TAG,
							"startActivityForResult : " + e.getMessage());
				}
			} else {
				Toast.makeText(this, "Please choose an Image...",
						Toast.LENGTH_LONG).show();
			}
		}
	}

	private void fnPostChopImage(Intent i) {
		Bundle extras = i.getExtras();
		Bitmap bm = extras.getParcelable("data");
		chosenImageView.setImageBitmap(bm);
		PrefHelper.fnSaveImage(this, mAppWidgetId, bm);
		fnUpdateView();
	}

	public void fnClose(View v) {
		this.fnExit();
	}

	@Override
	public void onResume() {
		super.onResume();
		LogHelper.log(TAG, "onResume");
		initData();
	}

	@Override
	public void onNewIntent(Intent newIntent) {
		LogHelper.log(TAG, "onNewIntent");
		super.onNewIntent(newIntent);
		this.setIntent(newIntent);
	}

	private void fnSetSeekBarListener(SeekBar sb) {
		final Context ctx = this;
		sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				if (fromUser == true) {
					seekbarAlphaLab.setText(seekLabel + progress);
				}
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				int p = seekBar.getProgress();
				seekbarAlphaLab.setText(seekLabel + p);
				PrefHelper.fnSaveAlphaPref(ctx, mAppWidgetId, p);
				fnUpdateView();
			}
		});
	}
}
